<?php
namespace app\index\Controller;
use app\index\model\User as UsersModel;
use app\index\model\Uploadfile as upLoad;
use think\Controller;
use think\Db;
use think\facade\Cache;

class User extends Controller{
    
    //  全局获取UID
    public static $uid;
    
    /**
    * @param register
    * @var username, mobile, password, ip
    */
    public function register(){
    
        $data = request()->put();
        $Users = new UsersModel();

        if ($Users->isUser($data["mobile"])>0) return json(["code"=>202,"msg"=>"该用户已存在!"]);
        if ($Users->addUser($data["mobile"],$data["password"],$data["ip"])>0){
            return json(["code"=>200,"msg"=>"注册成功!","data"=>request()->put()]);
        }else{
            return json(["code"=>500,"msg"=>"注册失败!"]);
        }
    }
    
    /**
     * @param login
     * @var mobile, password ,ip
     * returnStatus：0登陆成功,1用户不存在,2密码错误
     */
    public function login(){
        
        $data = request()->put();
        
        $Users = new UsersModel();
        
        if ($Users->isUser($data["mobile"])<1) return json(["code"=>1,"msg"=>"该用户不存在!"]); 
        $res = $Users->login($data["mobile"],$data["password"],$data["ip"]);
        
        if ($res){
            $token = $Users->generateToken($res["user_id"],[$res["user_id"],$res["mobile"]]);
            return json(["code"=>0,"msg"=>"登陆成功!","data"=>$res,"token"=>$token]);
        }else{
            return json(["code"=>2,"msg"=>"密码错误!"]);
        }
    }
    
    /*
    * 获取微信openid
    */
    public function wxlogin($code){
        $appid = "wx92fdf8424e98a3fe";
        $appsecret =  "9bb9bfc8a95f4525c07e1afbada1e569";
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=".$appid."&secret=".$appsecret."&grant_type=authorization_code&js_code=".$code;
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_REFERER, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        $result = curl_exec($ch);
        curl_close($ch);
            
        // $arr = '{"session_key":"5W0wWMo64cJMbR2dJDSOLw==","openid":"o4___4iAMsgrzwIGhWP2ZlzGWrk8"}';
        $res = json_decode($result, true);

        $data = request()->put();
        $Users = new UsersModel();
        
        $res2 = $Users->wxlogin($res["openid"], $data["nickname"], $data["head"]);
        
        if ($res){
            $token = $Users->generateToken($res2["user_id"],[$res2["user_id"],rand(1,1000)]);
            return json(["code"=>0,"msg"=>"登陆成功!","data"=>$res2,"token"=>$token]);
        }else{
            return json(["code"=>1,"msg"=>"未知错误!"]);
        }
        
        
    }
    
    
    
    
    
}
?>